package com.mycase.im.boot.websocket.pattern.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mycase.im.boot.entity.communication.ClientMessage;
import com.mycase.im.boot.entity.communication.ResponseMessage;
import com.mycase.im.boot.entity.database.ImFriendRequest;
import com.mycase.im.boot.entity.database.ImUser;
import com.mycase.im.boot.service.FriendRequestService;
import com.mycase.im.boot.service.UserService;
import com.mycase.im.boot.websocket.WebSocketSignal;
import com.mycase.im.boot.websocket.pattern.MessageStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.util.Map;

/**
 * 用来处理好友申请的策略器
 * @Author ZhuHJay
 * @Date 2021/9/18 21:06
 */
@Slf4j
@Service
public class FriendRequest implements MessageStrategy {

    @Autowired
    private FriendRequestService friendRequestService;
    @Autowired
    private UserService userService;

    @Override
    public Boolean isUse(int type) {
        return WebSocketSignal.MESSAGE_FRIEND_APPLY == type;
    }

    @Override
    public void executeHandler(ClientMessage clientMessage,
                               ObjectMapper objectMapper,
                               Map<String, Session> clientMaps,
                               Session mySession) throws Exception {
        log.warn("onMessage -匹配到-> FriendRequest(好友申请)");

        // 获取对应的请求信息, 可能有多条, 但是只获取最后一条
        ImFriendRequest imFriendRequest =
                friendRequestService.getLastApplyById(clientMessage.getFromId(), clientMessage.getToId());
        // 获取发送人和响应人的信息, 存放到该数据表中
        ImUser req = userService.getUserInfoById(imFriendRequest.getReqId());
        ImUser resp = userService.getUserInfoById(imFriendRequest.getRespId());
        imFriendRequest.setReqInfo(req);
        imFriendRequest.setRespInfo(resp);
        // 消息生成
        ResponseMessage responseMessage = ResponseMessage.success()
                    .appendData("imFriendRequest", imFriendRequest)
                    .appendData("type", WebSocketSignal.MESSAGE_FRIEND_APPLY);
        // 发送给自己
        sendMessage(objectMapper, mySession, responseMessage);
        // 如果被申请人在线就发送
        if( clientMaps.containsKey(imFriendRequest.getRespId()) ){
            sendMessage(objectMapper, clientMaps.get(imFriendRequest.getRespId()), responseMessage);
        }
    }
}
